package owe

import (
	"fmt"
	"github.com/gofiber/fiber/v2"
	"sg-backend/global"
	"sg-backend/model/paylog"
	"time"
)

type _addType struct {
	Type   string     `json:"type"`
	Money  float64    `json:"money"`
	Remark string     `json:"remark"`
	Time   *time.Time `json:"time"`
	ToWho  string     `json:"toWho"`
}

func AddOweLog(ctx *fiber.Ctx) error {
	// 解释数据
	var dataDto _addType
	if err := ctx.BodyParser(&dataDto); err != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": fmt.Sprintf("数据解释出错！%s", err),
		})
	}

	// 准备添加到数据库
	newLog := paylog.OweLog{
		UserId:       global.AuthUser.UserId,
		ToWho:        dataDto.ToWho,
		OweTime:      dataDto.Time,
		OweMoney:     dataDto.Money,
		PaybackMoney: 0,
		Done:         false,
		Remark:       dataDto.Remark,
	}

	r := global.DB.Create(&newLog)
	if r.Error != nil {
		return ctx.JSON(fiber.Map{
			"status":  "error",
			"message": "保存到数据库失败！" + r.Error.Error(),
		})
	}

	// 返回
	return ctx.JSON(fiber.Map{
		"status":  "done",
		"message": "保存成功！",
	})
}
